package com.feifan.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.feifan.api.service.ITokenService;
import com.feifan.api.service.IUserService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @program: FinalProject
 * @author: Xiaofan
 * @createTime: 2021-08-03 15:31
 * @description: Functions of this class is
 **/

@Service(version = "1.0.0",
        interfaceName = "com.feifan.api.service.ITokenService",
        interfaceClass = ITokenService.class
)
public class TokenService implements ITokenService {

    private static final long EXPIRE_TIME=7*1000000*60;//设置一个过期时间

    @Override
    public String getToken(String uesrId, String password) {

        return JWT.create().withAudience(uesrId).
                withExpiresAt(new Date(System.currentTimeMillis()+EXPIRE_TIME)).//设置过期时间
                sign(Algorithm.HMAC256(password));//通过该算法给密码进行加密处理;
    }

    @Override
    public String getUserId(String token) {
        return JWT.decode(token)   ///对token进行解码
                .getAudience().get(0);//取出里面的之前存的userid来
    }

    @Override
    public boolean checkSign(String token, String password) {
        if(token==null){
            throw new RuntimeException("token不存在，请重新登录！");
        }
        //如果token存在的话
        try{
            JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(password)).build();//通过该密码生成一个验证器与token进行比对
            jwtVerifier.verify(token);//如果没错的话，就不会抛出异常
        }
        catch (Exception e){
            throw new RuntimeException("token无效，请重新获取token！");
        }
        return true;
    }
}